package com.codemeta.bokit.comm.kit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Bean工具类
 *
 * @author hice
 */
public class BeanKit {

    /**
     * 计算对象的单差集，即只返回【对象1】中有，但是【对象2】中没有的元素
     *
     * @param obj1 .
     * @param obj2 .
     * @return .
     */
    public static Map<String, Object> subtract(Object obj1, Object obj2) {
        List<String> fields1 = getFieldNames(obj1.getClass());
        List<String> fields2 = getFieldNames(obj2.getClass());
        Collection<String> diffFieldNames = CollUtil.subtract(fields1, fields2);
        Map<String, Object> map = MapUtil.newHashMap();
        diffFieldNames.forEach(name -> map.put(name, BeanUtil.getFieldValue(obj1, name)));
        return map;
    }

    /**
     * 获取类的属性名集合
     *
     * @param clazz .
     * @return .
     */
    public static List<String> getFieldNames(Class<?> clazz) {
        final Field[] fields = ReflectUtil.getFields(clazz);
        return Arrays.stream(fields).map(Field::getName).collect(Collectors.toList());
    }
}